package com.css.dzj.dzjap.modules.enterprise.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.css.dzj.dzjap.common.util.*;
import com.css.dzj.dzjap.modules.enterprise.dao.EnterpriseDao;
import com.css.dzj.dzjap.modules.enterprise.entity.ApEnterpriseCreditEntity;
import com.css.dzj.dzjap.modules.enterprise.entity.QApEnterpriseCreditEntity;
import com.css.dzj.dzjap.modules.enterprise.service.EnterpriseService;
import com.css.dzj.dzjap.modules.info.service.EvalUnitService;
import com.css.dzj.dzjap.sys.user.entity.LoginUser;
import com.querydsl.core.QueryResults;
import com.querydsl.core.types.ExpressionUtils;
import com.querydsl.core.types.Predicate;
import com.querydsl.jpa.impl.JPAQueryFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class EnterpriseServiceImpl implements EnterpriseService {

    @Autowired
    private EnterpriseDao priseDao;

    @Value("${ZFJG_URL}")
    private String zfjgUrl;

    //注入JPAQueryFactory工厂
    @Autowired
    JPAQueryFactory jpaQueryFactory;
    @Autowired
    EvalUnitService evalUnitService;

    @Autowired
    HttpServletRequest request;

    @Autowired
    ServiceUtil serviceUtil;

    /**
     * 查询评价单位或建设单位信用信息表
     */
    @Override
    public ApEnterpriseCreditEntity getEnterPrise(String enterpriseCreditId , String enterpriseCredittype) {

        if(StringUtils.isEmpty(enterpriseCreditId) && StringUtils.isEmpty(enterpriseCredittype)){

            throw new RuntimeException("参数为空");
        }
        QApEnterpriseCreditEntity qPrise = QApEnterpriseCreditEntity.apEnterpriseCreditEntity;


         return jpaQueryFactory
            .selectFrom(qPrise)
            .where(  qPrise.enterpriseCreditId.eq(enterpriseCreditId),
                     qPrise.delFlag.eq(Constant.NO_DELETE),
                     qPrise.enterpriseCredittype.eq(enterpriseCredittype),
                     qPrise.excpresState.eq(Constant.EXCPRES_STATE_NO)
            )
            .fetchOne();
}

    /**
     * 添加评价单位或建设单位信用信息表
     */
    @Override
    @Transactional
    public String addEnterPrise(ApEnterpriseCreditEntity enterPrise) {

        if(!StringUtils.isEmpty(enterPrise) && !StringUtils.isEmpty(enterPrise.getCreditClueReasons())) {
            if("信用分类D".equals(enterPrise.getCreditClueReasons()) || "信用分类E".equals(enterPrise.getCreditClueReasons()) ||
                    "信用分类一次性下降≥2档".equals(enterPrise.getCreditClueReasons()) || "击中特定负面".equals(enterPrise.getCreditClueReasons())){
                // String enterpriseVO = JSON.toJSONString(enterPrise);
                String enterpriseVO = JSON.toJSONStringWithDateFormat(enterPrise,"yyyy-MM-dd", SerializerFeature.WriteDateUseDateFormat);
                String result = HttpClientUtil.doPostJson(zfjgUrl + "/clue/enterprisevo",enterpriseVO);
            }
        } else {
            throw new RuntimeException("企业信用信息或信用线索必填字段为空");
        }

        QApEnterpriseCreditEntity qPrise = QApEnterpriseCreditEntity.apEnterpriseCreditEntity;
        ApEnterpriseCreditEntity prise = jpaQueryFactory
                                           .selectFrom(qPrise)
                                           .where( qPrise.delFlag.eq(Constant.NO_DELETE),
                                                   qPrise.enterpriseScoreNumber.eq(enterPrise.getEnterpriseScoreNumber()).or(qPrise.enterpriseIdNumber.eq(enterPrise.getEnterpriseIdNumber()))
                                           )
                                           .fetchOne();
        if (prise!=null){
            throw new RuntimeException("评价单位评分编号或评价单位证件号码已存在！");
        }
        R r = serviceUtil.getUserInfoByRequest(request);
        if(r.getCode().equals("200")){
            LoginUser userInfo =  (LoginUser)r.get("data");
            enterPrise.setCreateUser(userInfo.getLoginName());
            enterPrise.setOrganName(userInfo.getOrgName());
        }
        enterPrise.setEnterpriseNotice("0");
        enterPrise.setDelFlag(Constant.NO_DELETE);
        enterPrise.setExcpresState(Constant.EXCPRES_STATE_NO);
        enterPrise.setCreateTime(new Date());
        try {
            priseDao.save(enterPrise);
            return enterPrise.getEnterpriseCreditId();

        }catch (Exception e){
            return "0";
        }

    }

    /**
     * 修改评价单位或建设单位信用信息表
     */
    @Override
    @Transactional
    public void update(ApEnterpriseCreditEntity enterPrise) {

    }

    /**
     * 删除评价单位或建设单位信用信息表
     */
    @Override
    @Transactional
    public Boolean deleteEnterPrise(String enterpriseCreditId, String enterpriseCredittype) {

        QApEnterpriseCreditEntity qPrise = QApEnterpriseCreditEntity.apEnterpriseCreditEntity;
        if(StringUtils.isEmpty(enterpriseCreditId)){
        return  false;
        }

        try{
            jpaQueryFactory
                    .update(qPrise)
                    .set(qPrise.delFlag,Constant.DELETE)
                    .where(
                            qPrise.enterpriseCreditId.eq(enterpriseCreditId),
                            qPrise.delFlag.eq(Constant.NO_DELETE),
                            qPrise.excpresState.eq(Constant.EXCPRES_STATE_NO),
                            qPrise.enterpriseCredittype.eq(enterpriseCredittype)
                    )
                    .execute();
            return true;
        }catch (Exception e){
            return false;
        }
    }


    /**
     * 查询评价单位或建设单位信用信息表黑名单
     */
    @Override
    public ApEnterpriseCreditEntity getReEnterPrise(String enterpriseCreditId, String enterpriseCredittype) {
        if(StringUtils.isEmpty(enterpriseCreditId) && StringUtils.isEmpty(enterpriseCredittype)){

            throw new RuntimeException("参数为空");
        }
        QApEnterpriseCreditEntity qPrise = QApEnterpriseCreditEntity.apEnterpriseCreditEntity;
        return jpaQueryFactory
                .selectFrom(qPrise)
                .where(  qPrise.enterpriseCreditId.eq(enterpriseCreditId),
                        qPrise.delFlag.eq(Constant.NO_DELETE),
                        qPrise.enterpriseCredittype.eq(enterpriseCredittype),
                        qPrise.excpresState.eq(Constant.EXCPRES_STATE_Yes)
                )
                .fetchOne();
    }


    /**
     *分页查询所有评价单位或建设单位信用信息表
     */
    @Override
    public QueryResults<ApEnterpriseCreditEntity> getAllEnterPrise(Pageable pageable ,String enterpriseCredittype,HttpServletRequest request) {

        QApEnterpriseCreditEntity qPrise = QApEnterpriseCreditEntity.apEnterpriseCreditEntity;
        Predicate predicate = qPrise.isNotNull().or(qPrise.isNull());
        predicate = ("".equals(enterpriseCredittype) || enterpriseCredittype == null) ? predicate : ExpressionUtils.and(predicate, qPrise.enterpriseCredittype.eq(enterpriseCredittype));
        predicate = ExpressionUtils.and(predicate, qPrise.delFlag.eq(Constant.NO_DELETE)) ;
        predicate = ExpressionUtils.and(predicate,qPrise.excpresState.eq(Constant.EXCPRES_STATE_NO));
        String orgName=ServiceUtil.getOrgName(request);
        if(orgName.contains("安评单位")) {
            String unsid = evalUnitService.findApIdCard(ServiceUtil.getLoginName(request));
            if (!StringUtils.isEmpty(unsid)) {
                    predicate = ExpressionUtils.and(predicate, qPrise.enterpriseIdNumber.eq(unsid));
            }
        }
        return  jpaQueryFactory
                .selectFrom(qPrise)
                .where(
                        predicate
                )
                .orderBy(qPrise.createTime.desc())
                .offset(pageable.getOffset())   //起始页
                .limit(pageable.getPageSize())  //每页大小
                .fetchResults();
    }

    /**
     *分页查询所有评价单位或建设单位信用信息表黑名单
     */
    @Override
    public QueryResults<ApEnterpriseCreditEntity> getAllReEnterPrise(Pageable pageable, String enterpriseCredittype,HttpServletRequest request) {

        QApEnterpriseCreditEntity qPrise = QApEnterpriseCreditEntity.apEnterpriseCreditEntity;
        Predicate predicate = qPrise.isNotNull().or(qPrise.isNull());
        predicate = ("".equals(enterpriseCredittype) || enterpriseCredittype == null) ? predicate : ExpressionUtils.and(predicate, qPrise.enterpriseCredittype.eq(enterpriseCredittype));
        predicate = ExpressionUtils.and(predicate, qPrise.delFlag.eq(Constant.NO_DELETE)) ;
        predicate = ExpressionUtils.and(predicate,qPrise.excpresState.eq(Constant.EXCPRES_STATE_Yes));
        String orgName=ServiceUtil.getOrgName(request);
        if(orgName.contains("安评单位")) {
            String unsid = evalUnitService.findApIdCard(ServiceUtil.getLoginName(request));
            if (!StringUtils.isEmpty(unsid)) {
                predicate = ExpressionUtils.and(predicate, qPrise.enterpriseIdNumber.eq(unsid));
            }
        }
        return  jpaQueryFactory
                .selectFrom(qPrise)
                .where(
                        predicate
                )
                .orderBy(qPrise.createTime.desc())
                .offset(pageable.getOffset())   //起始页
                .limit(pageable.getPageSize())  //每页大小
                .fetchResults();
    }



    /**
     *多条件分页查询所有评价单位或建设单位信用信息表
     */
    @Override
    public QueryResults<ApEnterpriseCreditEntity> getAllConEnterPrise(Pageable pageable, String enterpriseCredittype,String enterpriseName,String enterpriseScoreNumber,String enterpriseIdNumber,String enterpriseScore,String enterpriseClassification,String organName,HttpServletRequest request) {

        QApEnterpriseCreditEntity qPrise = QApEnterpriseCreditEntity.apEnterpriseCreditEntity;
        Predicate predicate = qPrise.isNotNull().or(qPrise.isNull());
        predicate = ("".equals(enterpriseCredittype) || enterpriseCredittype == null) ? predicate : ExpressionUtils.and(predicate, qPrise.enterpriseCredittype.eq(enterpriseCredittype));
        predicate = ("".equals(enterpriseName) || enterpriseName == null) ? predicate : ExpressionUtils.and(predicate, qPrise.enterpriseName.like("%"+enterpriseName+"%"));
        predicate = ("".equals(organName) || organName == null) ? predicate : ExpressionUtils.and(predicate, qPrise.organName.like("%"+organName+"%"));

        predicate = ("".equals(enterpriseScoreNumber) || enterpriseScoreNumber == null) ? predicate : ExpressionUtils.and(predicate, qPrise.enterpriseScoreNumber.like("%"+enterpriseScoreNumber+"%"));
        predicate = ("".equals(enterpriseIdNumber) || enterpriseIdNumber == null) ? predicate : ExpressionUtils.and(predicate, qPrise.enterpriseIdNumber.like("%"+enterpriseIdNumber+"%"));
        predicate = ("".equals(enterpriseScore) || enterpriseScore == null) ? predicate : ExpressionUtils.and(predicate, qPrise.enterpriseScore.eq(enterpriseScore));
        predicate = ("".equals(enterpriseClassification) || enterpriseClassification == null) ? predicate : ExpressionUtils.and(predicate, qPrise.enterpriseClassification.eq(enterpriseClassification));

        predicate = ExpressionUtils.and(predicate, qPrise.delFlag.eq(Constant.NO_DELETE)) ;
        predicate = ExpressionUtils.and(predicate,qPrise.excpresState.eq(Constant.EXCPRES_STATE_NO));
        String orgName=ServiceUtil.getOrgName(request);
        if(orgName.contains("安评单位")) {
            String unsid = evalUnitService.findApIdCard(ServiceUtil.getLoginName(request));
            if (!StringUtils.isEmpty(unsid)) {
                predicate = ExpressionUtils.and(predicate, qPrise.enterpriseIdNumber.eq(unsid));
            }
        }
        return  jpaQueryFactory
                .selectFrom(qPrise)
                .where(
                        predicate
                )
                .orderBy(qPrise.createTime.desc())
                .offset(pageable.getOffset())   //起始页
                .limit(pageable.getPageSize())  //每页大小
                .fetchResults();
    }


    /**
     *多条件分页查询所有评价单位或建设单位信用信息表黑名单
     */
    @Override
    public QueryResults<ApEnterpriseCreditEntity> getAllReConEnterPrise(Pageable pageable, String enterpriseCredittype,String enterpriseName,String enterpriseScoreNumber,String enterpriseIdNumber,String enterpriseScore,String enterpriseClassification,HttpServletRequest request) {

        QApEnterpriseCreditEntity qPrise = QApEnterpriseCreditEntity.apEnterpriseCreditEntity;
        Predicate predicate = qPrise.isNotNull().or(qPrise.isNull());
        predicate = ("".equals(enterpriseCredittype) || enterpriseCredittype == null) ? predicate : ExpressionUtils.and(predicate, qPrise.enterpriseCredittype.eq(enterpriseCredittype));
        predicate = ("".equals(enterpriseName) || enterpriseName == null) ? predicate : ExpressionUtils.and(predicate, qPrise.enterpriseName.like("%"+enterpriseName+"%"));

        predicate = ("".equals(enterpriseScoreNumber) || enterpriseScoreNumber == null) ? predicate : ExpressionUtils.and(predicate, qPrise.enterpriseScoreNumber.like("%"+enterpriseScoreNumber+"%"));
        predicate = ("".equals(enterpriseIdNumber) || enterpriseIdNumber == null) ? predicate : ExpressionUtils.and(predicate, qPrise.enterpriseIdNumber.like("%"+enterpriseIdNumber+"%"));
        predicate = ("".equals(enterpriseScore) || enterpriseScore == null) ? predicate : ExpressionUtils.and(predicate, qPrise.enterpriseScore.eq(enterpriseScore));
        predicate = ("".equals(enterpriseClassification) || enterpriseClassification == null) ? predicate : ExpressionUtils.and(predicate, qPrise.enterpriseClassification.eq(enterpriseClassification));

        predicate = ExpressionUtils.and(predicate, qPrise.delFlag.eq(Constant.NO_DELETE)) ;
        predicate = ExpressionUtils.and(predicate,qPrise.excpresState.eq(Constant.EXCPRES_STATE_Yes));
        String orgName=ServiceUtil.getOrgName(request);
        if(orgName.contains("安评单位")) {
            String unsid = evalUnitService.findApIdCard(ServiceUtil.getLoginName(request));
            if (!StringUtils.isEmpty(unsid)) {
                predicate = ExpressionUtils.and(predicate, qPrise.enterpriseIdNumber.eq(unsid));
            }
        }
        return  jpaQueryFactory
                .selectFrom(qPrise)
                .where(
                        predicate
                )
                .orderBy(qPrise.createTime.desc())
                .offset(pageable.getOffset())   //起始页
                .limit(pageable.getPageSize())  //每页大小
                .fetchResults();
    }

    /**
     * 通过统一信用代码查询评价单位或建设单位信用信息黑名单
     */
    @Override
    public ApEnterpriseCreditEntity getTyReConEnterPrise( String enterpriseCredittype, String enterpriseIdNumber) {
        if( StringUtils.isEmpty(enterpriseCredittype) && StringUtils.isEmpty(enterpriseIdNumber)){

            throw new RuntimeException("参数为空");
        }
        QApEnterpriseCreditEntity qPrise = QApEnterpriseCreditEntity.apEnterpriseCreditEntity;
        return jpaQueryFactory
                .selectFrom(qPrise)
                .where(
                         qPrise.delFlag.eq(Constant.NO_DELETE),
                         qPrise.enterpriseCredittype.eq(enterpriseCredittype),
                         qPrise.enterpriseIdNumber.eq(enterpriseIdNumber),
                         qPrise.excpresState.eq(Constant.EXCPRES_STATE_Yes)
                )
                .orderBy(qPrise.createTime.desc())
                .fetchOne();


    }

    /**
     *添加评价单位或建设单位信用信息黑名单
     */
    @Override
    @Transactional
    public String addReConEnterPrise(ApEnterpriseCreditEntity enterPrise) {

        QApEnterpriseCreditEntity qPrise = QApEnterpriseCreditEntity.apEnterpriseCreditEntity;
        ApEnterpriseCreditEntity prise = jpaQueryFactory
                .selectFrom(qPrise)
                .where(qPrise.delFlag.eq(Constant.NO_DELETE),
                        qPrise.enterpriseScoreNumber.eq(enterPrise.getEnterpriseScoreNumber()).or(qPrise.enterpriseIdNumber.eq(enterPrise.getEnterpriseIdNumber()))
                      )
                .fetchOne();
        if (prise!=null){
            throw  new RuntimeException("评价单位评分编号或评价单位证件号码已存在！");
        }
        R r = serviceUtil.getUserInfoByRequest(request);
        if(r.getCode().equals("200")){
            LoginUser userInfo =  (LoginUser)r.get("data");
            enterPrise.setCreateUser(userInfo.getLoginName());
            enterPrise.setOrganName(userInfo.getOrgName());
        }
        enterPrise.setDelFlag(Constant.NO_DELETE);
        enterPrise.setExcpresState(Constant.EXCPRES_STATE_Yes);
        enterPrise.setEnterpriseCreditId(SnowflakeId.getId());
        enterPrise.setCreateTime(new Date());
        enterPrise.setAbnormalPutdate(new Date());
        try {
            priseDao.save(enterPrise);
            return enterPrise.getEnterpriseCreditId();

        }catch (Exception e){
            return "0";
        }
    }

    /**
     *批量删除
     */
    @Override
    @Transactional
    public void update(List<ApEnterpriseCreditEntity> list) {

    }

    /**
     *等级认定
     */
    @Override
    @Transactional
    public Boolean updateEnterPriseList( List<ApEnterpriseCreditEntity> list) {
        if(list.size()<0 || list==null){

            throw  new RuntimeException("修改失败！");
        }
        QApEnterpriseCreditEntity qPrise = QApEnterpriseCreditEntity.apEnterpriseCreditEntity;

        try {
            for(int i = 0;i<list.size(); i++) {

                ApEnterpriseCreditEntity prise = list.get(i);
                jpaQueryFactory
                        .update(qPrise)
                        .set(qPrise.enterpriseScore, prise.getEnterpriseScore())
                        .set(qPrise.enterpriseClassification,prise.getEnterpriseClassification())
                        .set(qPrise.assessmentDate,prise.getAssessmentDate())
                        .set(qPrise.assessmentAuthority,prise.getAssessmentAuthority())
                        .set(qPrise.updateTime,new Date())
                        .where(
                                qPrise.enterpriseCreditId.eq(prise.getEnterpriseCreditId()),
                                qPrise.delFlag.eq(Constant.NO_DELETE)
                        )
                        .execute();//修改
            }
            return true;
        }catch (Exception e){
            return false;
        }


    }

    /**
     * 评价单位统一信用代码list
     */
    @Override
    @Transactional
    public List idNumber() {
        QApEnterpriseCreditEntity qPrise = QApEnterpriseCreditEntity.apEnterpriseCreditEntity;
        Predicate predicate = qPrise.isNotNull().or(qPrise.isNull());
        predicate = ExpressionUtils.and(predicate, qPrise.delFlag.eq(Constant.NO_DELETE)) ;
        predicate = ExpressionUtils.and(predicate,qPrise.excpresState.eq(Constant.EXCPRES_STATE_Yes));
        predicate = ExpressionUtils.and(predicate,qPrise.enterpriseCredittype.eq("0"));

        List<ApEnterpriseCreditEntity> list =jpaQueryFactory
                                                 .selectFrom(qPrise)
                                                  .where(
                                                          predicate
                                                        )//每页大小
                                                  .fetch();
       List idNumberList = new ArrayList();
        for(int i=0;i<list.size();i++){

            idNumberList.add(list.get(i).getEnterpriseIdNumber());
        }

        return idNumberList;
    }

    /**
     * 评价单位黑白名单表统一信用代码list
     */
    @Override
    @Transactional
    public List idHbNumber() {
        QApEnterpriseCreditEntity qPrise = QApEnterpriseCreditEntity.apEnterpriseCreditEntity;
        Predicate predicate = qPrise.isNotNull().or(qPrise.isNull());
        predicate = ExpressionUtils.and(predicate, qPrise.delFlag.eq(Constant.NO_DELETE)) ;
        predicate = ExpressionUtils.and(predicate,qPrise.enterpriseCredittype.eq("0"));

        List<ApEnterpriseCreditEntity> list =jpaQueryFactory
                .selectFrom(qPrise)
                .where(
                        predicate
                )//每页大小
                .fetch();
        List idHbNumberList = new ArrayList();
        for(int i=0;i<list.size();i++){

            idHbNumberList.add(list.get(i).getEnterpriseIdNumber());
        }

        return idHbNumberList;
    }
    /**
     * 评价单位在白名单中
     */
    @Override
    @Transactional
    public List idPJNumber() {
        QApEnterpriseCreditEntity qPrise = QApEnterpriseCreditEntity.apEnterpriseCreditEntity;
        Predicate predicate = qPrise.isNotNull().or(qPrise.isNull());
        predicate = ExpressionUtils.and(predicate, qPrise.delFlag.eq(Constant.NO_DELETE)) ;
        predicate = ExpressionUtils.and(predicate,qPrise.excpresState.eq(Constant.EXCPRES_STATE_NO));
        predicate = ExpressionUtils.and(predicate,qPrise.enterpriseCredittype.eq("0"));
        List<ApEnterpriseCreditEntity> list =jpaQueryFactory
                .selectFrom(qPrise)
                .where(
                        predicate
                )//每页大小
                .fetch();
        List idNumberList = new ArrayList();
        for(int i=0;i<list.size();i++){

            idNumberList.add(list.get(i).getEnterpriseIdNumber());
        }

        return idNumberList;
    }


}
